<template>
  <div
    class="app-container calendar-list-container"
    v-loading="loading"
    element-loading-text="正在导出数据"
  >
    <!-- 查询条件 -->
    <div class="filter-container">
      <el-form :inline="true" ref="form1" :model="listQuery">
        <el-form-item label="产品品号" prop="produceNo">
          <el-input disabled clearable style="width: 120px;" v-model="listQuery.produceNo" />
        </el-form-item>
        <el-form-item label="客户编码" prop="clientNumber">
          <el-input disabled clearable style="width: 120px;" v-model="listQuery.clientNumber" />
        </el-form-item>
        <el-form-item label="型号描述" prop="produceName">
          <el-input disabled clearable style="width: 200px;" v-model="listQuery.produceName" />
        </el-form-item>
        <el-form-item label="产品版本" prop="version">
          <el-input disabled clearable style="width: 120px;" v-model="listQuery.version" />
        </el-form-item>
        <el-form-item label="作业工序" prop="processName">
          <el-select
            v-model="sopItem.processName"
            placeholder="请选择"
            @change="processNameChange(sopItem.processName)"
            filterable
            clearable
            size="mini"
            style="width: 150px"
          >
            <el-option
              v-for="item in processJobClass"
              :key="item.processId"
              :label="item.processName"
              :value="item.processName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="作业名称" prop="assignmentName">
          <el-input clearable style="width: 300px;" v-model="sopItem.assignmentName" />
        </el-form-item>
      </el-form>
    </div>

    <!-- 主体区域 -->
    <el-container class="main-body">
      <!-- 左侧作业内容 -->
      <el-aside width="300px" style="background: #f5f5f5; padding: 1px;">
        <!-- 作业步骤 -->
        <div class="box" style="flex: 7;">
          <div
            class="box-title"
            style="display: flex; justify-content: space-between; align-items: center;"
          >
            <span>作业步骤</span>
            <el-button
              type="text"
              icon="el-icon-plus"
              @click="addStep"
              style="font-size: 15px; padding: 0;"
            ></el-button>
          </div>
          <el-scrollbar class="scroll-box" wrap-style="overflow-x: hidden;">
            <div v-for="(step, index) in sopItemSteps" :key="'step' + index" class="step-line">
              <span style="width: 20px;">{{ index + 1}}.</span>
              <el-input
                v-model="step.content"
                type="textarea"
                placeholder="请输入步骤内容"
                size="small"
                :autosize="{ minRows: 1, maxRows: 6 }"
                style="width: calc(100% - 18px);"
              />
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="removeStep(index)"
                style="font-size: 15px; padding: 0;"
              ></el-button>
            </div>
            <!-- 添加一个空占位 div -->
            <div style="height: 15px;"></div>
          </el-scrollbar>
        </div>

        <!-- 注意事项 -->
        <div class="box" style="flex: 3;">
          <div
            class="box-title yellow"
            style="display: flex; justify-content: space-between; align-items: center;"
          >
            <span>注意事项</span>
            <el-button
              type="text"
              icon="el-icon-plus"
              @click="addNotice"
              style="font-size: 15px; padding: 0;"
            ></el-button>
          </div>
          <el-scrollbar class="scroll-box" wrap-style="overflow-x: hidden;">
            <div
              v-for="(notice, index) in sopItemPrecautions"
              :key="'notice' + index"
              class="step-line"
            >
              <span style="width: 20px;">{{ index + 1 }}.</span>
              <el-input
                v-model="notice.content"
                type="textarea"
                placeholder="请输入注意事项"
                size="small"
                :autosize="{ minRows: 1, maxRows: 6 }"
                style="width: calc(100% - 18px);"
              />
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="removeNotice(index)"
                style="font-size: 15px; padding: 0;"
              ></el-button>
            </div>
            <!-- 添加一个空占位 div -->
            <div style="height: 15px;"></div>
          </el-scrollbar>
        </div>
      </el-aside>

      <!-- 中间上传和图片展示 -->
      <el-main style="padding: 10px;">
        <el-upload
          class="pdf-uploader"
          action="http://192.168.3.11:8086/technologyFile"
          :on-success="handlePdfSuccess"
          :on-remove="removePdf"
          :on-change="pdfRemove"
          :headers="getHttpHeader"
          :before-upload="beforeFilsUpload"
          :show-file-list="false"
        >
          <div v-if="sopItem.img" class="pdf-preview">
            <img
              :src="sopItem.img"
              alt="预览图"
              style="width: 100%; height: 100%; object-fit: contain;"
            />
            <!-- <div class="file-name" style="margin-top: 4px;">{{ fileName }}</div> -->
          </div>
          <div v-else class="upload-placeholder">
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <div>点击上传图片</div>
          </div>
        </el-upload>
      </el-main>
    </el-container>

    <!-- 三个横向表格 -->
    <div class="table-section">
      <!-- 工具 -->
      <div class="table-wrapper" style="flex: 2.5;">
        <div class="table-title" style="display: flex; align-items: center; margin-bottom: 8px;">
          <span style="margin-right: 6px;">使用工具</span>
          <el-button
            type="text"
            icon="el-icon-plus"
            @click="addTool"
            style="font-size: 15px; padding: 0;"
          ></el-button>
        </div>
        <el-table :data="sopItemTools" border style="width: 100%;" height="250">
          <el-table-column label="序号" width="45">
            <template slot-scope="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>

          <el-table-column label="工具名称" width="260">
            <template slot-scope="scope">
              <el-cascader
                v-model="scope.row.selectedTool"
                :options="toolCascaderOptions"
                :props="{ expandTrigger: 'hover' }"
                :filterable="true"
                @change="handleToolChange($event, scope.row)"
                clearable
                size="small"
                :class="{'cascader-no-arrow': !scope.row.editing}"
                style="width: 100%;"
                placeholder="请选择工具"
              />
            </template>
          </el-table-column>

          <el-table-column prop="facilityBarcodeType3" label="规格/方法" width="90" />

          <el-table-column label="操作" width="45">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="removeTool(scope.$index)"
                style="font-size: 15px; padding: 0;"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 工装检具 -->
      <div class="table-wrapper" style="flex: 2.5;">
        <div class="table-title" style="display: flex; align-items: center; margin-bottom: 8px;">
          <span style="margin-right: 6px;">工装/检具</span>
          <el-button
            type="text"
            icon="el-icon-plus"
            @click="addInspectionTool"
            style="font-size: 15px; padding: 0;"
          ></el-button>
        </div>
        <el-table :data="sopItemInspectionToolList" border style="width: 100%;" height="250">
          <el-table-column label="序号" width="45">
            <template slot-scope="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="类别" width="260">
            <template slot-scope="scope">
              <el-cascader
                v-model="scope.row.selectedInspectionTool"
                :options="inspectionToolCascaderOptions"
                :props="{ expandTrigger: 'hover' }"
                :filterable="true"
                @change="handleInspectionToolChange($event, scope.row)"
                clearable
                size="small"
                style="width: 100%;"
                placeholder="请选择类别"
              />
            </template>
          </el-table-column>
          <el-table-column prop="facilityBarcodeType3" label="规格型号" width="90" />
          <el-table-column label="操作" width="45">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="removeInspectionTool(scope.$index)"
                style="font-size: 15px; padding: 0;"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 使用物料 -->
      <div class="table-wrapper" style="flex: 5;">
        <div class="table-title" style="display: flex; align-items: center; margin-bottom: 8px;">
          <span style="margin-right: 6px;">使用物料</span>
          <el-button
            type="text"
            icon="el-icon-plus"
            @click="addMaterialData"
            style="font-size: 15px; padding: 0;"
          ></el-button>
        </div>
        <el-table :data="materialRows" border style="width: 100%;" height="250">
          <!-- 左列 -->
          <el-table-column label="序号" width="50">
            <template slot-scope="scope">{{ scope.row.left && scope.row.left.index }}</template>
          </el-table-column>
          <el-table-column label="物料编码" width="140">
            <template slot-scope="scope">
              <el-select
                v-if="scope.row.left"
                v-model="scope.row.left.materialCode"
                placeholder="请选择"
                @change="onMaterialCodeChange(scope.row.left)"
                filterable
                clearable
                size="mini"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in materialBom"
                  :key="item.materialCode"
                  :label="item.materialCode"
                  :value="item.materialCode"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="规格描述">
            <template slot-scope="scope">{{ scope.row.left ? scope.row.left.materialName : '' }}</template>
          </el-table-column>
          <el-table-column label="数量" width="80">
            <template slot-scope="scope">
              <el-input
                @keypress.native="onlyNumber"
                @change="handleQtyChange(scope.row, 'left')"
                v-if="scope.row.left"
                v-model="scope.row.left.qty"
                :min="0"
                :style="{ width: '100%' }"
                size="mini"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="45">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="removeMaterialData(scope.row.left)"
                style="font-size: 15px; padding: 0;"
              ></el-button>
            </template>
          </el-table-column>

          <!-- 右列 -->
          <el-table-column label="序号" width="50">
            <template slot-scope="scope">{{ scope.row.right && scope.row.right.index }}</template>
          </el-table-column>
          <el-table-column label="物料编码" width="140">
            <template slot-scope="scope">
              <el-select
                v-if="scope.row.right"
                v-model="scope.row.right.materialCode"
                placeholder="请选择"
                @change="onMaterialCodeChange(scope.row.right)"
                filterable
                clearable
                size="mini"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in materialBom"
                  :key="item.materialCode"
                  :label="item.materialCode"
                  :value="item.materialCode"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="规格描述">
            <template slot-scope="scope">{{ scope.row.right ? scope.row.right.materialName : '' }}</template>
          </el-table-column>
          <el-table-column label="数量" width="80">
            <template slot-scope="scope">
              <el-input
                @keypress.native="onlyNumber"
                @change="handleQtyChange(scope.row, 'right')"
                v-if="scope.row.right"
                v-model="scope.row.right.qty"
                :min="0"
                :style="{ width: '100%' }"
                size="mini"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="45">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.right"
                type="text"
                icon="el-icon-delete"
                @click="removeMaterialData(scope.row.right)"
                style="font-size: 15px; padding: 0;"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 底部信息区域 -->
    <div class="bottom-info" style="display: flex; gap: 10px; padding: 10px;">
      <!-- 左侧信息 -->
      <div
        class="bottom-info-item"
        style="flex: 8; background: #f9f9f9; padding: 10px; border-radius: 8px;"
      >
        <el-form :model="listQuery" label-width="87px">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="公司名称">
                <el-input v-model="listQuery.companyName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="制定人">
                <el-input v-model="listQuery.createName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="审核人">
                <el-input v-model="listQuery.reviewerName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="批准人">
                <el-input v-model="listQuery.approverName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="作业人数">
                <el-select v-model="sopItem.userQty" placeholder="请选择人数" style="width: 100%;">
                  <el-option label="1" :value="1"></el-option>
                  <el-option label="2" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="文件编号">
                <el-input v-model="listQuery.fileNumber" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="制定日期">
                <el-input v-model="listQuery.createTime" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="审核日期">
                <el-input v-model="listQuery.reviewDate" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="批准日期">
                <el-input v-model="listQuery.approveDate" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="标准工时(s)">
                <el-input v-model="sopItem.machineTime" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 右侧分页按钮 -->
      <div
        class="bottom-info-select"
        style="flex: 2; background: #f4f6fa; padding: 20px; border-radius: 8px;"
      >
        <el-form :model="listQuery" label-width="68px">
          <el-row :gutter="10" style="margin-bottom: 20px;">
           <el-col :span="24">
            <el-form-item label="页面顺序" prop="pageSequence">
              <div style="display: flex; align-items: center; gap: 10px;">
                <!-- 页面顺序输入框 -->
                <el-input-number
                  v-model="sopItem.pageSequence"
                  :min="1"
                  :step="1"
                  style="width: 120px;"
                />

                <!-- 第X页 共Y页 -->
                <div style="display: flex; align-items: center; gap: 6px;">
                  <span>第</span>
                  <el-input v-model="sopItem.pageNumber" size="small" style="width: 65px;"  />
                  <span>页</span>
                  <span>共</span>
                  <el-input v-model="sopItem.count" size="small" style="width: 60px;" disabled />
                  <span>页</span>
                </div>
              </div>
            </el-form-item>
          </el-col>
          </el-row>

          <el-row :gutter="10" style="text-align: center;">
            <el-col :span="4">
              <el-button
                type="text"
                size="small"
                icon="el-icon-arrow-left"
                @click="prevPage"
                style="font-size: 15px; padding: 0;"
              >上一页</el-button>
            </el-col>
            <el-col :span="4">
              <el-button
                type="text"
                size="small"
                @click="jumpPage"
                style="font-size: 15px; padding: 0;"
              >跳转</el-button>
            </el-col>
            <el-col :span="4">
              <el-button
                type="text"
                size="small"
                style="font-size: 15px; padding: 0;"
                @click="nextPage"
              >
                下一页
                <i class="el-icon-arrow-right" style="margin-left: 5px;"></i>
              </el-button>
            </el-col>
            <el-col :span="6">
              <el-button
                type="text"
                size="small"
                icon="el-icon-plus"
                @click="addPage"
                style="font-size: 15px; padding: 0;"
              >新增</el-button>
            </el-col>
            <el-col :span="6">
              <el-button
                type="text"
                size="small"
                icon="el-icon-delete"
                @click="removePage"
                style="font-size: 15px; padding: 0;"
              >删除</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getEmsFacility,
  getMaterialBom,
  getProcessByProduceNo,
  saveSopItemDraft,
  getSopItem,
  removeSopItemPage,
  checkBomQty
} from "@/api/processRoute";
export default {
  name: "SOPmain",
  props: {
    sop: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      listQuery: {
        produceNo: "",
        clientNumber: "",
        produceName: "",
        orderType: "",
        workCenter: ""
      },
      sopItem: {
        processId: null,
        processName: "",
        pageNumber: 1,
        count: 1,
        img: ""
      },
      sopItemSteps: [],
      sopItemPrecautions: [],

      getHttpHeader: {
        Authorization: "",
        CHECK_USER_VALUE: "GOLWAY",
        CHECK_PASSWORD_VALUE: "8D4DD3F80CEB6149329FDBD590B164F1"
      },
      // 表格数据
      sopItemTools: [],
      toolMap: {},
      toolCascaderOptions: [],
      sopItemInspectionToolList: [],
      inspectionToolMap: {},
      inspectionToolCascaderOptions: [],
      sopItemMaterials: [],
      materialBom: [],
      processJobClass: [],
      loading: false
    };
  },
  computed: {
    cascaderOptions() {
      // 转为 el-cascader 支持的格式
      return Object.entries(this.toolMap).map(([key, items]) => ({
        label: key,
        value: key,
        children: items.map(child => ({
          label: child.facilityBarcodeType3,
          value: child.facilityBarcodeType3,
          data: child // 传递完整对象用于回填
        }))
      }));
    },
    cascaderProps() {
      return {
        value: "value",
        label: "label",
        children: "children"
      };
    },
    materialRows() {
      const result = [];
      for (let i = 0; i < this.sopItemMaterials.length; i += 2) {
        result.push({
          left: this.sopItemMaterials[i],
          right: this.sopItemMaterials[i + 1] || null
        });
      }
      // 添加序号（1-based）
      result.forEach((row, i) => {
        if (row.left) row.left.index = i * 2 + 1;
        if (row.right) row.right.index = i * 2 + 2;
      });
      return result;
    }
  },
  methods: {
    async handleQtyChange(row, side) {
      const qty = row[side].qty;

      // 校验是否为有效数字且大于0
      if (isNaN(qty) || qty <= 0) {
        this.$message.error("数量必须大于0！");
        row[side].qty = ""; // 清空输入框
        return;
      }
      const id = row[side].id;
      // 调用接口检查是否超限
      try {
        let query = {
          sopId: this.listQuery.id,
          materialId: row[side].id,
          materialCode: row[side].materialCode,
          qty: qty
        };
        let data = await checkBomQty(query);
        if (data.code != 1) {
          this.$message.error(data.msg);
          row[side].qty = ""; // 清空输入框
        }
      } catch (error) {
        console.error("检查数量限制失败：", error);
        this.$message.error("检查数量失败，请稍后重试！");
      }
    },
    onlyNumber(e) {
      const key = e.key;
      if (isNaN(key) && key !== ".") e.preventDefault();
    },
    async saveMain() {
      this.loading = true;
      let query = {
        sop: this.listQuery,
        sopItem: {
          id: this.sopItem.id,
          sopId: this.listQuery.id,
          processId: this.sopItem.processId,
          processName: this.sopItem.processName,
          pageSequence: this.sopItem.pageSequence,
          assignmentName: this.sopItem.assignmentName,
          pageNumber: this.sopItem.pageNumber,
          userQty: this.sopItem.userQty,
          machineTime: this.sopItem.machineTime,
          img: this.sopItem.img
        },
        sopItemInspectionToolList: this.sopItemInspectionToolList,
        sopItemMaterials: this.sopItemMaterials,
        sopItemPrecautions: this.sopItemPrecautions,
        sopItemSteps: this.sopItemSteps,
        sopItemTools: this.sopItemTools
      };
      let data = await saveSopItemDraft(query);
      if (data.code == "1") {
        this.getSopItem();
        this.$message({
          type: "success",
          message: "保存成功"
        });
      }
      this.loading = false;
    },
    async addPage() {
      if (!this.sopItem.id) {
        return this.$message.warning("请先在先保存当前页！！！");
      }
      let pageNumber = this.sopItem.pageNumber;
      let count = this.sopItem.count;
      let processId = this.sopItem.processId;
      let processName = this.sopItem.processName;
      this.sopItemInspectionToolList = [];
      this.sopItemMaterials = [];
      this.sopItemPrecautions = [];
      this.sopItemSteps = [];
      this.sopItemTools = [];
      this.sopItem = {};
      this.sopItem.pageNumber = count + 1;
      this.sopItem.count = count + 1;
      this.sopItem.processId = processId;
      this.sopItem.processName = processName;
    },
    async removePage() {
      await removeSopItemPage({ sopItemId: this.sopItem.id });
      this.getSopItem();
    },
    addStep() {
      const nextIndex =
        this.sopItemSteps.length > 0
          ? this.sopItemSteps[this.sopItemSteps.length - 1].index + 1
          : 1;
      this.sopItemSteps.push({ index: nextIndex, content: "" });
    },
    removeStep(index) {
      this.sopItemSteps.splice(index, 1);
      this.sopItemSteps.forEach((step, i) => {
        step.index = i + 1;
      });
    },
    addNotice() {
      const nextIndex =
        this.sopItemPrecautions.length > 0
          ? this.sopItemPrecautions[this.sopItemPrecautions.length - 1].index +
            1
          : 1;
      this.sopItemPrecautions.push({ index: nextIndex, content: "" });
    },
    removeNotice(index) {
      this.sopItemPrecautions.splice(index, 1);
      this.sopItemPrecautions.forEach((notice, i) => {
        notice.index = i + 1;
      });
    },
    addTool() {
      this.sopItemTools.push({ name: "" });
    },
    removeTool(index) {
      this.sopItemTools.splice(index, 1);
    },
    addInspectionTool() {
      this.sopItemInspectionToolList.push({ name: "" });
    },
    removeInspectionTool(index) {
      this.sopItemInspectionToolList.splice(index, 1);
    },

    addMaterialData() {
      this.sopItemMaterials.push({ materialCode: "" });
    },
    removeMaterialData(index) {
      const realIndex = this.sopItemMaterials.findIndex(
        item => item.index === index.index
      );
      if (realIndex !== -1) {
        this.sopItemMaterials.splice(realIndex, 1);
      }
      this.sopItemMaterials.forEach((item, i) => {
        item.index = i + 1;
      });
    },
    async jumpPage() {
      let query = {
        sopId: this.listQuery.id,
        processId: this.sopItem.processId,
        sopItemId: this.sopItem.id,
        pageNumber: this.sopItem.pageNumber,
        pageType: "jump"
      };
      let data = await getSopItem(query);
      if (data.code == 1) {
        const d = data.data || {};
        let processId = this.sopItem.processId;
        let processName = this.sopItem.processName;
        this.sopItemMaterials = d.sopItemMaterials || [];
        this.sopItemPrecautions = d.sopItemPrecautions || [];
        this.sopItemSteps = d.sopItemSteps || [];
        this.sopItemInspectionToolList = (d.sopItemInspectionToolList || []).map(row => {
          const toolName = row.facilityName; // 这是 toolCascaderOptions 的第一级 value
          const barcodeType3 = row.facilityBarcodeType3; // 这是第二级 value
          return {
            ...row,
            selectedInspectionTool:toolName && barcodeType3 ? [toolName, barcodeType3] : []
          };
        });
        this.sopItemTools = (d.sopItemTools || []).map(row => {
          const toolName = row.facilityName; // 这是 toolCascaderOptions 的第一级 value
          const barcodeType3 = row.facilityBarcodeType3; // 这是第二级 value
          return {
            ...row,
            selectedTool:toolName && barcodeType3 ? [toolName, barcodeType3] : []
          };
        });
        this.sopItem = d.sopItem || {};
        this.sopItem.processId = processId;
        this.sopItem.processName = processName;
      } else {
        this.$message.error(data.msg);
      }
    },
    async nextPage() {
      let query = {
        sopId: this.listQuery.id,
        processId: this.sopItem.processId,
        sopItemId: this.sopItem.id,
        pageType: "down"
      };
      let data = await getSopItem(query);
      if (data.code == 1) {
        const d = data.data || {};
        let processId = this.sopItem.processId;
        let processName = this.sopItem.processName;
        this.sopItemMaterials = d.sopItemMaterials || [];
        this.sopItemPrecautions = d.sopItemPrecautions || [];
        this.sopItemSteps = d.sopItemSteps || [];
        this.sopItemInspectionToolList = (d.sopItemInspectionToolList || []).map(row => {
          const toolName = row.facilityName; // 这是 toolCascaderOptions 的第一级 value
          const barcodeType3 = row.facilityBarcodeType3; // 这是第二级 value
          return {
            ...row,
            selectedInspectionTool:toolName && barcodeType3 ? [toolName, barcodeType3] : []
          };
        });
        this.sopItemTools = (d.sopItemTools || []).map(row => {
          const toolName = row.facilityName; // 这是 toolCascaderOptions 的第一级 value
          const barcodeType3 = row.facilityBarcodeType3; // 这是第二级 value
          return {
            ...row,
            selectedTool:toolName && barcodeType3 ? [toolName, barcodeType3] : []
          };
        });
        this.sopItem = d.sopItem || {};
        this.sopItem.processId = processId;
        this.sopItem.processName = processName;
      } else {
        this.$message.error(data.msg);
      }
    },
    async prevPage() {
      let query = {
        sopId: this.listQuery.id,
        processId: this.sopItem.processId,
        sopItemId: this.sopItem.id,
        pageType: "up"
      };
      let data = await getSopItem(query);
      if (data.code == 1) {
        const d = data.data || {};
        let processId = this.sopItem.processId;
        let processName = this.sopItem.processName;
        this.sopItemMaterials = d.sopItemMaterials || [];
        this.sopItemPrecautions = d.sopItemPrecautions || [];
        this.sopItemSteps = d.sopItemSteps || [];
         this.sopItemInspectionToolList = (d.sopItemInspectionToolList || []).map(row => {
          const toolName = row.facilityName; // 这是 toolCascaderOptions 的第一级 value
          const barcodeType3 = row.facilityBarcodeType3; // 这是第二级 value
          return {
            ...row,
            selectedInspectionTool:toolName && barcodeType3 ? [toolName, barcodeType3] : []
          };
        });
        this.sopItemTools = (d.sopItemTools || []).map(row => {
          const toolName = row.facilityName; // 这是 toolCascaderOptions 的第一级 value
          const barcodeType3 = row.facilityBarcodeType3; // 这是第二级 value
          return {
            ...row,
            selectedTool:toolName && barcodeType3 ? [toolName, barcodeType3] : []
          };
        });
        this.sopItem = d.sopItem || {};
        this.sopItem.processId = processId;
        this.sopItem.processName = processName;
      } else {
        this.$message.error(data.msg);
      }
    },
    cleanProcess() {
      this.sopItem.processId = "";
      this.sopItem.processName = "";
    },
    async getSopItem() {
      let query = {
        sopId: this.listQuery.id,
        processId: this.sopItem.processId,
        pageNumber: 1
      };
      let data = await getSopItem(query);
      if (data.code == 1) {
        const d = data.data || {};
        let processId = this.sopItem.processId;
        let processName = this.sopItem.processName;
        this.sopItemInspectionToolList = (d.sopItemInspectionToolList || []).map(row => {
          const toolName = row.facilityName; // 这是 toolCascaderOptions 的第一级 value
          const barcodeType3 = row.facilityBarcodeType3; // 这是第二级 value
          return {
            ...row,
            selectedInspectionTool:toolName && barcodeType3 ? [toolName, barcodeType3] : []
          };
        });
        this.sopItemTools = (d.sopItemTools || []).map(row => {
          const toolName = row.facilityName; // 这是 toolCascaderOptions 的第一级 value
          const barcodeType3 = row.facilityBarcodeType3; // 这是第二级 value
          return {
            ...row,
            selectedTool:toolName && barcodeType3 ? [toolName, barcodeType3] : []
          };
        });
        this.sopItemMaterials = d.sopItemMaterials || [];
        this.sopItemPrecautions = d.sopItemPrecautions || [];
        this.sopItemSteps = d.sopItemSteps || [];
        this.sopItem = d.sopItem || {};
        this.sopItem.processId = processId;
        this.sopItem.processName = processName;
      } else {
        this.$message.error(data.msg);
      }
    },
    async getProcessByProduceNo() {
      let data = await getProcessByProduceNo({
        produceNo: this.listQuery.produceNo
      });
      if (data.code == 1) {
        this.processJobClass = data.data;
      } else {
        this.$message.error(data.msg);
      }
    },
    async getMaterialBom() {
      if (
        this.listQuery.workCenter != null &&
        this.listQuery.workCenter != ""
      ) {
        let data = await getMaterialBom({
          materialCode: this.listQuery.produceNo
        });
        if (data.code == 1) {
          this.materialBom = data.data;
        } else {
          this.$message.error(data.msg);
        }
      }
    },
    async getEmsFacility() {
      if (
        this.listQuery.workCenter != null &&
        this.listQuery.workCenter != ""
      ) {
        let data = await getEmsFacility({
          workCenter: this.listQuery.workCenter
        });
        if (data.code == 1) {
          this.toolMap = data.data.gj;
          this.inspectionToolMap = data.data.jj;
          //  在数据获取成功后，构建级联数据
          this.toolCascaderOptions = Object.entries(this.toolMap).map(
            ([name, items]) => {
              return {
                label: name,
                value: name,
                children: items.map(item => ({
                  label: item.facilityBarcodeType3,
                  value: item.facilityBarcodeType3
                }))
              };
            }
          );
          this.inspectionToolCascaderOptions = Object.entries(
            this.inspectionToolMap
          ).map(([name, items]) => {
            return {
              label: name,
              value: name,
              children: items.map(item => ({
                label: item.facilityBarcodeType3,
                value: item.facilityBarcodeType3
              }))
            };
          });
        } else {
          this.$message.error(data.msg);
        }
      }
    },
    handleToolChange(val, row) {
      // 清空了
      if (!val || val.length === 0) {
        row.emsFacilityId = null;
        row.facilityName = '';
        row.facilityBarcodeType3 = '';
        row.selectedTool = [];
        return;
      }
      const [toolName, type3] = val;

      const matched = (this.toolMap[toolName] || []).find(
        item => item.facilityBarcodeType3 === type3
      );

      if (matched) {
        row.emsFacilityId = matched.id;
        row.facilityName = matched.facilityName;
        row.facilityBarcodeType3 = matched.facilityBarcodeType3;
      }
    },
    handleInspectionToolChange(val, row) {
      // 清空了
      if (!val || val.length === 0) {
        row.emsFacilityId = null;
        row.facilityName = '';
        row.facilityBarcodeType3 = '';
        row.selectedInspectionTool = [];
        return;
      }
      const [toolName, type3] = val;

      const matched = (this.inspectionToolMap[toolName] || []).find(
        item => item.facilityBarcodeType3 === type3
      );

      if (matched) {
        row.emsFacilityId = matched.id;
        row.facilityName = matched.facilityName;
        row.facilityBarcodeType3 = matched.facilityBarcodeType3;
      } else {
        row = {}
      }
    },
    onMaterialCodeChange(row) {
      const match = this.materialBom.find(
        item => item.materialCode === row.materialCode
      );

      if (!match) {
        row.materialName = "";
        row.qty = null; // 清空数量
        return;
      }

      // 检查当前物料是否已在 sopItemMaterials 中存在（排除自身）
      const isMaterialExist = this.sopItemMaterials.some(
        item => item.materialCode === row.materialCode && item !== row
      );

      if (isMaterialExist) {
        this.$message.error("该物料已存在，请勿重复添加！");
        row.materialCode = ""; // 清空物料编码
        row.materialName = ""; // 清空物料名称
        row.qty = null; // 清空数量
        return;
      }

      // 如果物料未重复，则更新信息
      row.materialName = match.materialName;
      row.specs = match.specs;
      row.unit = match.unit;
    },
    processNameChange(val) {
      const match = this.processJobClass.find(item => item.processName === val);
      if (match) {
        this.sopItem.processId = match.processId;
      }
      this.getSopItem();
    },
    receiveListQuery(data) {
      this.listQuery = Object.assign({}, this.listQuery, data);
    },
    pdfRemove(e) {
      if (e.status == "fail") return this.$message.error("文件上传失败!");
      else if (e.status == "success")
        return this.$message.success("文件上传成功!");
    },
    async removePdf(file) {
      this.sopItem.img = "";
      console.log(file, "removePdf");
    },
    handlePdfSuccess(response) {
      this.sopItem.img = response.results;
    },
    beforeFilsUpload(file) {
      this.getHttpHeader.Authorization = this.dealCookie();
    },
    dealCookie() {
      const strcookie = document.cookie;
      const arrcookie = strcookie.split("; ");
      for (let i = 0; i < arrcookie.length; i++) {
        const arr = arrcookie[i].split("=");
        if (arr[0] == "agent_Authorization") return arr[1];
      }
      return "";
    }
  },
  mounted() {}
};
</script>

<style scoped>
/* 主体区域高度 */
.main-body {
  height: 60vh;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 左侧容器 */
.el-aside {
  display: flex;
  flex-direction: column;
  gap: 10px;
  background: #f9f9f9 !important;
  border-right: 1px solid #e0e0e0;
  box-sizing: border-box;
}

/* 通用 box 样式 */
.box {
  background: #fff;
  border-radius: 6px;
  padding: 2px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
}

/* 标题样式 */
.box-title {
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 0px;
  color: #333;
}

/* 黄色标题样式 */
.box-title.yellow {
  color: #e6a23c;
}

/* 步骤行 */
.step-line {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.pdf-uploader {
  width: 100%;
  height: 100%;
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  background-color: #fafafa;
  transition: 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 14px;
}

.avatar-uploader-icon {
  font-size: 36px;
  color: #409eff;
  margin-bottom: 8px;
}

/* 步骤 & 注意事项布局比例控制 */
.el-aside {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.pdf-preview {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
}

.table-section {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  gap: 10px;
}
.table-title {
  background: #f2f2f2;
  font-weight: bold;
  padding: 6px;
  text-align: center;
  margin-bottom: 4px;
}
</style>
